let App = getApp()
let config = {
    domain: App.globalData.requestUrl,//项目域名
    cdn:  App.globalData.cdnUrl  //图片cdn域名
}
class Http {
    request(method, api, data, loading = false, toast = true) {
        let token = wx.getStorageSync('token')
        let info = {
            url: config.domain + api,
            data,
            timeout: 500000,  // 设置请求超时时间为 50分钟
            header: {
                'content-type': 'application/json',
                'token': token
            },
            method: method,
            timeout: 0
        }
        return new Promise((resolve, reject) => {
            if (loading) {
                wx.showLoading({
                    title: '加载中',
                    mask: true,
                })
            }
            wx.request({
                ...info,
                success: (result) => {
                    if (result.data.code === 401) {
                        wx.navigateTo({
                            url: '/service/login/login',
                        })
                        reject(result)
                    }
                    if (result.data.code !== 200) {
                        if (toast) {
                            wx.showToast({
                                title: (result && result.data && result.data.msg) ? result.data.msg : '请稍后重试',
                                icon: 'none',
                                duration: 2000
                            })
                        } else {
                            reject(result)
                        }
                    } else {
                        resolve(result.data)
                    }
                },
                fail: (res) => {
                    reject(res)
                },
                complete: (res) => {
                    wx.hideLoading({
                        noConflict: true
                    })
                },
            })
        })
    }
    post(url, data, loading, toast = false, ) {
        return this.request('POST', url, data, loading, toast, )
    }
    get(url, data, loading, toast = false, ) {
        return this.request('GET', url, data, loading, toast, )
    }
}
const http = new Http()
module.exports = http